package com.icexxx.lathe;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class IceSessionUtil {

    public static String sessionId() {
        Class<?> securityUtilsClass = null;
        try {
            securityUtilsClass = Class.forName("org.apache.shiro.SecurityUtils");
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        }
        Object subject = null;
        String sessionId = null;
        try {
            Method subjectMethod = securityUtilsClass.getMethod("getSubject");
            subject = subjectMethod.invoke(null);
            if (subject == null) {
                return null;
            }
            Class<?> subjectClass = (Class<?>) subject.getClass();
            Object session = null;
            Method sessionMethod = subjectClass.getMethod("getSession");
            session = sessionMethod.invoke(subject);
            if (session == null) {
                return null;
            }
            Class<?> sessionClass = (Class<?>) session.getClass();
            Method sessionIdMethod = sessionClass.getMethod("getId");
            sessionId = (String) sessionIdMethod.invoke(session);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        if (sessionId != null) {
            return sessionId.replace("-", "");
        }
        return null;
    }

}
